// 天气数据API
import { get, post } from './request.js'

// 高德地图天气API配置
const AMAP_WEATHER_KEY = 'd93428c62f0f8fcbcbe1be9e05893e41' // 从manifest.json获取的key
const AMAP_WEATHER_BASE_URL = 'https://restapi.amap.com/v3/weather'

// 获取实时天气数据
export const getRealtimeWeather = async (city = '郑州市') => {
  try {
    const url = `${AMAP_WEATHER_BASE_URL}/weatherInfo`
    const params = {
      key: AMAP_WEATHER_KEY,
      city: city,
      extensions: 'all' // 获取详细信息
    }
    
    // 构建查询字符串
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&')
    
    const response = await uni.request({
      url: `${url}?${queryString}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.status === '1' && response.data.forecasts && response.data.forecasts.length > 0) {
      const weatherData = response.data.forecasts[0]
      const casts = weatherData.casts[0] // 今天的数据
      
      return {
        success: true,
        data: {
          city: weatherData.city,
          reportTime: weatherData.reportTime,
          temperature: casts.temp_high || '25', // 最高温度
          humidity: casts.humidity || '65', // 湿度
          windDirection: casts.winddir || casts.wind_dir || '北风', // 风向（尝试多个字段）
          windSpeed: parseFloat(casts.windpower || casts.wind_power) || 3.5, // 风力等级转换为风速
          weather: casts.weather || '晴', // 天气状况
          pressure: '1013.25' // 气压（高德API不提供，使用默认值）
        }
      }
    } else {
      throw new Error('天气数据获取失败')
    }
  } catch (error) {
    console.error('获取天气数据失败:', error)
    return {
      success: false,
      error: error.message,
      data: {
        city: city,
        temperature: '25',
        humidity: '65',
        windDirection: '东北风',
        windSpeed: 3.5,
        weather: '晴',
        pressure: '1013.25'
      }
    }
  }
}

// 获取未来几天的天气预报
export const getWeatherForecast = async (city = '郑州市', days = 3) => {
  try {
    const url = `${AMAP_WEATHER_BASE_URL}/weatherInfo`
    const params = {
      key: AMAP_WEATHER_KEY,
      city: city,
      extensions: 'all'
    }
    
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&')
    
    const response = await uni.request({
      url: `${url}?${queryString}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.status === '1' && response.data.forecasts && response.data.forecasts.length > 0) {
      const weatherData = response.data.forecasts[0]
      const forecasts = weatherData.casts.slice(0, days)
      
      return {
        success: true,
        data: forecasts.map(cast => ({
          date: cast.date,
          temperature: cast.temp_high,
          humidity: cast.humidity,
          windDirection: cast.winddir,
          windSpeed: parseFloat(cast.windpower) || 3.5,
          weather: cast.weather
        }))
      }
    } else {
      throw new Error('天气预报获取失败')
    }
  } catch (error) {
    console.error('获取天气预报失败:', error)
    return {
      success: false,
      error: error.message,
      data: []
    }
  }
}

// 根据城市名称获取坐标
export const getCityLocation = async (city = '郑州市') => {
  try {
    const url = 'https://restapi.amap.com/v3/geocode/geo'
    const params = {
      key: AMAP_WEATHER_KEY,
      address: city
    }
    
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&')
    
    const response = await uni.request({
      url: `${url}?${queryString}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.status === '1' && response.data.geocodes && response.data.geocodes.length > 0) {
      const location = response.data.geocodes[0].location.split(',')
      return {
        success: true,
        data: {
          longitude: parseFloat(location[0]),
          latitude: parseFloat(location[1])
        }
      }
    } else {
      throw new Error('城市坐标获取失败')
    }
  } catch (error) {
    console.error('获取城市坐标失败:', error)
    return {
      success: false,
      error: error.message,
      data: {
        longitude: 114.305392,
        latitude: 30.592849
      }
    }
  }
}

// 获取周边POI信息（学校、医院、居民区等）
export const getNearbyPOI = async (longitude, latitude, radius = 3000, poiType = 'all') => {
  try {
    const url = 'https://restapi.amap.com/v3/place/around'
    const params = {
      key: AMAP_WEATHER_KEY,
      location: `${longitude},${latitude}`,
      radius: radius,
      types: poiType, // 学校：141200, 医院：090000, 居民区：120000, 商业：060000
      output: 'json'
    }
    
    const queryString = Object.keys(params)
      .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
      .join('&')
    
    const response = await uni.request({
      url: `${url}?${queryString}`,
      method: 'GET',
      header: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.data.status === '1' && response.data.pois) {
      return {
        success: true,
        data: response.data.pois.map(poi => ({
          name: poi.name,
          type: poi.type,
          address: poi.address,
          distance: poi.distance,
          location: poi.location
        }))
      }
    } else {
      throw new Error('POI数据获取失败')
    }
  } catch (error) {
    console.error('获取周边POI失败:', error)
    return {
      success: false,
      error: error.message,
      data: []
    }
  }
}

// 获取学校信息
export const getNearbySchools = async (longitude, latitude, radius = 3000) => {
  return await getNearbyPOI(longitude, latitude, radius, '141200')
}

// 获取医院信息
export const getNearbyHospitals = async (longitude, latitude, radius = 3000) => {
  return await getNearbyPOI(longitude, latitude, radius, '090000')
}

// 获取居民区信息
export const getNearbyResidential = async (longitude, latitude, radius = 3000) => {
  return await getNearbyPOI(longitude, latitude, radius, '120000')
}

// 获取商业区信息
export const getNearbyCommercial = async (longitude, latitude, radius = 3000) => {
  return await getNearbyPOI(longitude, latitude, radius, '060000')
}

// 默认导出
export default {
  getRealtimeWeather,
  getWeatherForecast,
  getCityLocation,
  getNearbyPOI,
  getNearbySchools,
  getNearbyHospitals,
  getNearbyResidential,
  getNearbyCommercial
}
